<template>
  <div>
    <el-form ref="form" :model="commodity" :rules="rules" label-width="80px">

      <el-form-item label="名称" prop="c_name">
      <el-input v-model="commodity.c_name"></el-input>
    </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-input v-model="commodity.type"></el-input>
      </el-form-item>
      <el-form-item label="价格" prop="c_price">
        <el-input v-model="commodity.c_price"></el-input>
      </el-form-item>
      <el-form-item label="库存" prop="c_num">
        <el-input v-model="commodity.c_num"></el-input>
      </el-form-item>
      <el-form-item label="描述" prop="c_describe">
        <el-input v-model="commodity.c_describe"></el-input>
      </el-form-item>
      <el-form-item label="爆款" prop="c_hot">
        <!--<el-input v-model="commodity.c_hot"></el-input>-->
        <template>
          <el-radio v-model="commodity.c_hot" label="1">爆</el-radio>
          <el-radio v-model="commodity.c_hot" label="0">不爆</el-radio>
        </template>
      </el-form-item>
      <el-form-item label="图片">
        <img :src="commodity.c_photopath" width="50px">
        <el-upload ref="upload" name="photo" action="" :auto-upload="false"
                   accept=".png,.jpg,.gif" :on-change="handleChange"
                   :file-list="fileList" :http-request="httpRequest"
        >
          <el-button type="primary" size="small">点击上传</el-button>
          <span slot="tip">.png,.jpg,.gif</span>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">立即创建</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  export default {
    data(){
      return{
        commodity:{
          c_name:'',
          c_price:'',
          c_num:'',
          c_describe:'',
          c_hot:'',
          c_photopath:'',
          type:''
        },
        fileList:[],
        file:[],
        rules:{

        },
      }
    },
    methods:{
      onSubmit(){
        this.$refs.form.validate(valid=>{
          if (valid){
            var formData = new FormData();
            this.$refs.upload.submit();
            this.file.forEach(function(file){
              console.log(file);
              formData.append('photo',file,file.name);
            });
            Object.keys(this.commodity).forEach(key=>{
              formData.append(key,this.commodity[key])
            });
            this.$axios.post('/CommodityServlet/addCommodity',formData)
              .then(resp=>{
                this.$router.push('/commodity/list')
              })
          }
        })
      },
      handleChange(file){
        this.fileList.splice(0,this.fileList.length)
        this.commodity.c_photopath=URL.createObjectURL(file.raw)
        this.fileList[0]=file;
      },
      httpRequest(param){
        this.file.push(param.file)
      },
    },
  }
</script>

<style scoped>

</style>
